package com.hlkj.baojin.soket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSoket extends Thread {
    final Logger logger = LoggerFactory.getLogger(this.getClass());
    ServerSocket server = null;
    Socket sk = null;
    BufferedReader rdr = null;
    PrintWriter wtr = null;

    public ServerSoket() {
        try {
            server = new ServerSocket(new Integer(9116));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void run() {
        while (true) {
            logger.info("ServerSoket Starting...");
            try {
//                  每个请求交给一个线程去处理
                sk = server.accept();
                ServerThread th = new ServerThread(sk);
                th.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
    class ServerThread extends Thread {
        Socket sk = null;
        public ServerThread(Socket sk) {
            this.sk = sk;
        }
        public void run() {
            try {
                wtr = new PrintWriter(sk.getOutputStream());
                rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                logger.info("New connection accepted " + sk.getInetAddress() + ":" + sk.getPort());

                while (true) {
                    String line = rdr.readLine();
                    logger.info("Client msg:" + line);
                    wtr.println("ok");
                    wtr.flush();
                    logger.info("server to client  result ok! ");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
//            finally {
//                try {
//                    if (sk != null) sk.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

        }

    }
}
